package netty_rpc;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务端操作：获取发送过来的信息，通过反射获得类名，根据函数名和参数值，执行具体的操作，将执行结果发送给客户端
 */
public class InvokerHandler extends ChannelInboundHandlerAdapter {
    public static ConcurrentHashMap<String,Object> classMap=new ConcurrentHashMap<>();
    public void channelRead(ChannelHandlerContext ctx,Object msg)throws Exception{
        ClassInfo classInfo=(ClassInfo) msg;
        Object claszz=null;
        if (!classMap.containsKey(classInfo.getClassName())){
            try {
                claszz=Class.forName(classInfo.getClassName()).newInstance();
                classMap.put(classInfo.getClassName(),claszz);
            }catch (InstantiationException|IllegalAccessException|ClassNotFoundException e){
                e.printStackTrace();
            }
        }else {
            claszz=classMap.get(classInfo.getClassName());
        }
        Method method=claszz.getClass().getMethod(classInfo.getMethodName(),classInfo.getTypes());
        Object result=method.invoke(claszz,classInfo.getObjects());
        ctx.write(result);
        ctx.flush();
        ctx.close();

    }

    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause)throws Exception{
        cause.printStackTrace();
        ctx.close();
    }

}
